import Database from '@tauri-apps/plugin-sql';

class DB {
  private db: Database | null = null;

  // 初始化数据库连接
  async connect(dbType: 'sqlite' | 'postgres' | 'mysql', config: string) {
    if (this.db) return;
    this.db = await Database.load(`${dbType}:${config}`);
  }

  // 执行 SQL 语句 (增、删、改)
  async execute(query: string, bindValues?: any[]) {
    if (!this.db) throw new Error('Database not initialized');
    return await this.db.execute(query, bindValues);
  }

  // 查询数据
  async query<T = any>(query: string, bindValues?: any[]): Promise<T[]> {
    if (!this.db) throw new Error('Database not initialized');
    return await this.db.select(query, bindValues);
  }

  // 关闭连接
  async close() {
    if (!this.db) return;
    await this.db.close();
    this.db = null;
  }

  // 事务处理
  async transaction(callback: () => Promise<void>) {
    if (!this.db) throw new Error('Database not initialized');
    await this.db.execute('BEGIN');
    try {
      await callback();
      await this.db.execute('COMMIT');
    } catch (err) {
      await this.db.execute('ROLLBACK');
      throw err;
    }
  }
}

export const db = new DB();